import { defineConfig } from "vite";
import path from "path";
import pkg from "./package.json";

function getRollOpts(peerDependencies) {
  if (!peerDependencies) return {};
  const keys = Object.keys(peerDependencies);
  const obj: any = {};
  keys.forEach((key: string) => {
    obj[key] = key;
  });
  return {
    external: keys,
    output: {
      // preserveModules: true, // 防止tree-shaking移除未使用的导出
      globals: obj,
    },
  };
}

export default defineConfig({
  server: {
    port: 4003, //启动端口
  },
  resolve: {
    // extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json"],
    extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json", ".svg"],
    alias: {
      // 放在根目录下时
      "@": path.resolve(__dirname, "lib"),
      "~": path.resolve(__dirname, "src"),
      // mock: path.join(__dirname, "mock"),
    },
    // dedupe: [], // 如果你在你的应用程序中有相同依赖的副本（比如 monorepos），请使用此选项强制 Vite 始终将列出的依赖项解析为同一副本（从项目根目录）
    // conditions: [],
    // mainFields: [],
    // preserveSymlinks: [],
  },
  build: {
    lib: {
      entry: "./lib/index.ts",
      name: "index",
      formats: ["es", "cjs"], // 生成ES和CommonJS格式
      // fileName: "index",
      fileName: (format) => `index.${format}.js`,
    },
    // 其他配置
    rollupOptions: getRollOpts(pkg.peerDependencies),
  },
});
